package cn.qidd.keep.order.service.impl;

import cn.qidd.keep.domain.core.dict.MemberStatus;
import cn.qidd.keep.domain.core.dict.WhetherStatus;
import cn.qidd.keep.domain.document.Member;
import cn.qidd.keep.domain.document.Order;
import cn.qidd.keep.domain.web.BusinessException;
import cn.qidd.keep.domain.web.UserVO;
import cn.qidd.keep.order.feignclient.MemberServiceClient;
import cn.qidd.keep.order.model.order.CreateOrderRequest;
import cn.qidd.keep.order.repository.OrderRepository;
import cn.qidd.keep.order.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private MemberServiceClient memberServiceClient;
    @Resource
    private OrderRepository orderRepository;

    @Override
    public void createOrder(UserVO userVO, CreateOrderRequest request) {
        if (request.getIsMember().equals(WhetherStatus.YES)) {
            // 校验会员
            this.validMember(request.getMemberNo());
            // 更新会员
            if (request.getIsMember().equals(WhetherStatus.YES)) {
                memberServiceClient.updateMember(request.getMemberNo());
            }
        }
        Order order = new Order();
        BeanUtils.copyProperties(request, order);
        order.setCreateTime(new Date());
        order.setOperatorName(userVO.getUserName());
        order.setOperatorRealName(userVO.getRealName());
        order.setOperatorTime(new Date());
        order.setOrderNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
        orderRepository.save(order);
    }

    private void validMember(String memberNo) {
        if (StringUtils.isBlank(memberNo)) {
            throw new BusinessException("请输入正确的会员编号");
        }
        boolean exist = memberServiceClient.isExist(memberNo);
        if (!exist) {
            throw new BusinessException("请输入正确的会员编号");
        }
        Member member = memberServiceClient.getMemberByMemberNo(memberNo);
        if (member.getMemberStatus().equals(MemberStatus.FINISHED)) {
            throw new BusinessException("会员次数已用完");
        }
        if (member.getMemberStatus().equals(MemberStatus.INVALID)) {
            throw new BusinessException("会员已失效");
        }
        Integer count = member.getLeaveCount();
        if (count < 1) {
            throw new BusinessException("会员次数已用完");
        }
    }
}
